package logic

import (
	"afb/models/cache"
	"afb/models/mysql"
	"afb/pkg"
	"afb/zfbrpc/internal/svc"
	"afb/zfbrpc/zfbrpc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zfbrpc.LoginRequest) (*zfbrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var users mysql.Userr
	if in.Mobile != "" {
		mysql.DB.Debug().Where("username =?", in.Username).Find(&users)
		if users.ID == 0 {
			return nil, fmt.Errorf("当前用户未注册,请前往去注册")
		}
		get := cache.Rdb.Get(l.ctx, "captcha"+in.Username)
		if get.Val() != in.SmsCode {
			return nil, fmt.Errorf("验证码错误,情重新输入")
		}
	}
	if in.Username != "" {
		get := cache.Rdb.Get(l.ctx, "captcha"+in.Username)
		if get.Val() != in.CaptchaCode {
			return nil, fmt.Errorf("当前密码错误,请重新输入")
		}
		mysql.DB.Debug().Where("username =?", in.Username).Find(&users)

		if pkg.Md5(in.Password) != users.Password {
			return nil, fmt.Errorf("密码错误不对")
		}
		if users.ID == 0 {
			return nil, fmt.Errorf("当前帐号不存在,请前去注册")
		}
	}
	mysql.DB.Debug().Create(&users)
	return &zfbrpc.LoginResponse{
		UserId: int64(users.ID),
	}, nil
}
